using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using DevComponents.DotNetBar;
using DevComponents.DotNetBar.Metro;
using Microsoft.Office.Interop.Excel;
using OfficeOpenXml;
using OfficeOpenXml.Style;
using PlatForm.Controller;
using PlatForm.DataLayer;

namespace PlatForm.Presentation
{
    public partial class frmKPIReport : MetroForm
    {
        private KPIController kpiCtrl = new KPIController();

        public frmKPIReport()
        {
            InitializeComponent();
            dgvKPI.AutoGenerateColumns = false;
        }

        private void btnReport_Click(object sender, EventArgs e)
        {
            var lstKPI = kpiCtrl.GetAll(dtpKPIDate.Value);
            dgvKPI.DataSource = lstKPI;
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            var x = saveFileDialog1.ShowDialog();
            if (x==DialogResult.OK)
            {
                var tempFile = new FileInfo(saveFileDialog1.FileName);
                if (tempFile.Exists)
                {
                    tempFile.Delete(); // ensures we create a new workbook
                    tempFile = new FileInfo(saveFileDialog1.FileName);
                }
                using (var package = new ExcelPackage(tempFile))
                {
                    // add a new worksheet to the empty workbook
                    ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Kpi");

                    //format table
                    worksheet.Cells.Style.Border.Right.Style = ExcelBorderStyle.Thin;
                    worksheet.Cells.Style.Border.Right.Color.SetColor(Color.LightGray);
                    worksheet.Cells["A1:S1"].Style.Font.Bold = true;

                    foreach (DataGridViewColumn c in dgvKPI.Columns)
                    {
                        worksheet.Cells[1, c.Index + 1].Value = c.HeaderText;
                    }

                    foreach (DataGridViewRow r in dgvKPI.Rows)
                    {
                        foreach (DataGridViewColumn c in dgvKPI.Columns)
                        {
                            worksheet.Cells[r.Index+2, c.Index + 1].Value = r.Cells[c.Index].Value.ToString();
                        }
                    }

                    worksheet.Cells.Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
                    worksheet.Cells.Style.VerticalAlignment = ExcelVerticalAlignment.Center;

                    worksheet.Cells.AutoFitColumns(0); //Autofit columns for all cells
                    worksheet.DefaultRowHeight = 30;


                    package.Save();
                }
            }
        }
    }
}